import io from "socket.io-client"

import { getCookie } from "libs/cookie"
import { dispatch } from "store"

import {HOST} from "libs/api"

let socket = io(`${HOST}:9098`)
socket.on("connect", () => {
  console.info("建立連接")
  if (getCookie("token")) {bindToken()}
  disconnectListener()
  messageListener()
})

function reconnect () {
  console.info("开始重连")
  socket = io(`${HOST}:9098`)
  socket.on("connect", () => {
    console.info("重连成功")
    disconnectListener()
    messageListener()
  })
}

function disconnectListener () {
  socket.on("disconnect", () => {
    console.info("連接断开")
    reconnect()
  })
}

function messageListener () {
  socket.on("message", (data) => {
    console.info(data)
    dispatch({
      type: "ADD_MESSAGE",
      data
    })
  })
}

export function bindToken () {
  console.info("绑定token")
  socket.emit("bindToken", {token: getCookie("token")})
}
